import {
  Component,
  OnInit,
  Optional,
  Inject,
  ChangeDetectorRef,
  OnChanges,
  ViewChild,
  Output,
  EventEmitter,
  Input,
} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, NG_ASYNC_VALIDATORS, NgModel } from '@angular/forms';
import { ElementBase } from 'src/app/benshuo/util/form/element-base';
import { MajorDTO } from 'src/app/benshuo/model/major-dto';
import { MajorService } from 'src/app/benshuo/services/major.service';
import { NzSelectComponent, NzTreeNode } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { CollectionHelper } from 'src/app/benshuo/util/data/collection-helper';
import { MapUtil } from 'src/app/benshuo/util/map/map-util';
@Component({
  selector: 'app-major-select',
  templateUrl: './major-select.component.html',
  styleUrls: ['./major-select.component.less'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: MajorSelectComponent,
      multi: true,
    },
  ],
})
export class MajorSelectComponent extends ElementBase<Array<MajorDTO>> implements OnInit, OnChanges {
  /**
   * 项目标段的数据，ID做key，用于快速查找
   */
  private sections: Map<string, MajorDTO> = new Map<string, MajorDTO>();
  /**
   * model的实例
   */
  @ViewChild(NgModel, null)
  model: NgModel;

  /**
   * 勾选事件
   */
  @Output()
  checkedEvent = new EventEmitter<Array<MajorDTO>>();

  /**
   * TreeSelect的实例
   */
  @ViewChild('nzselect', null)
  nzselect: NzSelectComponent;

  /**
   * 请求状态
   */
  isLoading = false;

  /**
   * 下拉初始数据
   */
  nodes = [];

  /**
   * 树节点数组
   */
  treeNodes: Array<NzTreeNode> = [];

  /**
   * 单个树节点对象
   */
  treeNode: NzTreeNode;

  /**
   * 树节点对象
   */
  data = null;

  values = [];

  constructor(
    private majorService: MajorService,
    @Optional() @Inject(NG_VALIDATORS) validators: Array<any>,
    @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<any>,
    private cdr: ChangeDetectorRef,
  ) {
    super(validators, asyncValidators);
  }

  ngOnInit() {
    this.load();
  }

  load() {
    this.isLoading = true;
    // tslint:disable-next-line: deprecation
    this.majorService.getAll().subscribe(
      data => {
        if (data) {
          this.sections = MapUtil.arrayToMap(data);
          this.nodes = data;
        }
      },
      null,
      () => {
        this.isLoading = false;
      },
    );
  }

  /**
   * 选择事件
   * @param $event 选择的值 选择的值 多选下返回的是数组
   */
  select($event) {
    if ($event === null || $event.length === 0) {
      this.value = [];
      return;
    }
    if (typeof $event === 'string') {
      this.value = [this.sections.get($event)];
    } else {
      if ($event.length > 0) {
        this.value = $event.map(s => {
          return this.sections.get(s);
        });
        // tslint:disable-next-line:no-string-literal
      } else if ($event['id'] !== null) {
        // tslint:disable-next-line:no-string-literal
        this.value = [this.sections.get($event['id'])];
      }
    }
    // this.value = [...$event];
    this.checkedEvent.emit(this.value);
  }

  /**
   * 传入参数变化时的处理
   * @param changes 变化的参数
   */
  ngOnChanges(changes) {
    console.log(1);
  }

  writeValue(value: Array<any>) {
    super.writeValue(value);
    this.convertDetailItem(value);
  }

  /**
   * 覆盖信息
   */
  convertDetailItem(value: Array<any>) {
    this.cdr.detectChanges();
    console.log(value);
    if (value) {
      this.values = this.value.map(v => {
        return v.id;
      });
    }
    if (!value) {
      this.nzselect.value = null;
      this.value = null;
    }
  }
}
